"""
Retrieves a specific post from Blogger in HTML format.
This service relies on a Yahoo! Pipe to function.

@example: /srv/s1/blog-id/post-id/

@author Jean-Lou Dupont
"""
import os
import wsgiref.handlers
from google.appengine.ext           import webapp
#from google.appengine.ext.webapp    import template
from libs.wiki import template
from google.appengine.api           import urlfetch

import xml.dom.minidom 

class Service_S1( webapp.RequestHandler ):
    """Retrieves a specific post from Blogger in HTML format
        Usage: /srv/s1/blog-id/post-id/
    """

    PIPE_URL = "http://pipes.yahoo.com/jldupont/filterblogger?_render=rss&blogid=%s&postid=%s"
        
    def get(self, blog_id, post_id ):
    
        url = self.PIPE_URL % ( blog_id, post_id )
        result = urlfetch.fetch( url )
    
        if ( result.status_code != 200 ):
            return
        
        rss = xml.dom.minidom.parseString( result.content );   
        assert rss.documentElement.tagName == "rss"
        
        ce = rss.documentElement.getElementsByTagName( 'channel' );
        ie = ce[0].getElementsByTagName( 'item' );
        de = ie[0].getElementsByTagName( 'description' );
        d = de[0].firstChild.data
        
        template_values = { 'description': d };
        
        # Path to the template
        path = os.path.join(os.path.dirname(__file__), 'template.html')
        
        # template replacement & rendering
        self.response.out.write(template.render(path, template_values))

#/**
# *  Initialize http handler
# */
def main():
  application = webapp.WSGIApplication( [('/srv/s1/(.*?)/(.*)/', Service_S1)], debug=True)
  wsgiref.handlers.CGIHandler().run(application)

# Bootstrap
#  It all starts here
if __name__ == "__main__":
  main()